package parent

import (
	"anban/controllers"
	"anban/service"
	"anban/utils"
	"fmt"
	"html/template"
	"net/url"
)

type StudentController struct {
	controllers.BaseController
}

func (c *StudentController) ProtectMember() {
	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	p = map[string]interface{}{}
	p["relation"] = true
	p["familySn"] = user.FamilySn
	c.Data["memberNum"], c.Data["memberList"] = service.GetStudentList(p)

	c.Data["title"] = "守护成员"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/protect-member.html"
}

func (c *StudentController) AddProtectMember() {
	var res *utils.ResJsonStruct
	input := c.Input()

	if len(input["real_name"][0]) <= 0 {
		res = utils.ResJson(0, "请输入姓名", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["id_card"][0]) <= 0 {
		res = utils.ResJson(0, "请输入身份证号", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	p := map[string]interface{}{}
	p["realName"] = input["real_name"][0]
	p["idCard"] = input["id_card"][0]
	student := service.GetStudentInfo(p)
	if student.Id <= 0 {
		res = utils.ResJson(0, "姓名或身份证号不正确", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(student.FamilySn) > 0 {
		res = utils.ResJson(0, fmt.Sprintf("添加失败，%s已经存在了", input["real_name"][0]), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var addInput url.Values
	var editInput url.Values

	userId := c.GetSession("userId")
	p = map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	p = map[string]interface{}{}
	p["familySn"] = user.FamilySn
	_, parentMemberList := service.GetUserList(p)
	for _, parentMember := range parentMemberList {
		addInput = url.Values{
			"user_id": {fmt.Sprintf("%d", parentMember.Id)},
			"student_id": {fmt.Sprintf("%d", student.Id)},
		}
		_, err := service.AddUserStudent(addInput)
		if err != nil {
			res = utils.ResJson(0, "操作失败，请稍候重试", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
	}

	editInput = url.Values{
		"id": {fmt.Sprintf("%d", student.Id)},
		"family_sn": {user.FamilySn},
	}
	service.EditStudent(editInput)

	res = utils.ResJson(1, "操作成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}
